<template>
    <Select
            :value="sel_val"
            :clearable="clearable"
            :label-in-value="labelAndVal"
            :element-id='id'
            :multiple='multiple'
            :filterable='filterable'
            :size='size'
            :placeholder='placeholder'
            :labelAndVal='labelAndVal'
            :placement='placement'
            :disabled='disabled'


            @on-change='changeFun'
            @on-query-change='changeSearch'
            @on-clear='clearFun'
            @on-open-change='openChangeFun'
    >
        <Option v-for="item in options" :value="item.value" :key="item.value">{{ item.label }}</Option>
    </Select>
</template>

<script>
  import {postAction} from '@/api/request'
  export default {
    name:'dictSelect',
    props:{
      disabled: {
        type: Boolean,
        default: false
      },
      clearable: {//是否可以清空选项，只在单选时有效
        type: Boolean,
        default: false
      },
      multiple: { //是否支持多选
        type: Boolean,
        default: false
      },
      filterable: { //是否支持搜索,多选搜索时，可以使用键盘Delete快捷删除最后一个已选项
        type: Boolean,
        default: false
      },
      labelAndVal: { //选择框默认文字,ture是只返回value,false是label和value 一并返回
        type: Boolean,
        default: true
      },
      size: String, //选择框大小，可选值为large、small、default或者不填
      placeholder: String, //选择框默认文字
      placement: String, //选择框默认文字-弹窗的展开方向，可选值为 top、bottom、top-start、bottom-start、top-end、bottom-end
      id:String,//给表单元素设置 id
      sel_val: [String,Number,Array],//单选时只接受 String 或 Number，多选时只接受 Array
      dicType:{ // code、table、service，code时取sys_dict，table时取表，service时直接调用接口
        type: String,
        default: 'code'
      },
      dictCode:String,
      dictTable:String, //字符串格式，英文逗号分隔，数据库标识(可选，如果不填默认为业务库),表名,字段码,字段明文， 例：subsistence(可选),ss01001,azaa0001,azaa0002
      dictService:String,
      showKeys:String,  //需要显示的键值，其他隐藏
      hideKeys:String, //需要隐藏的键值，其他显示
      serviceParam: { //dictService的入参
        type: Object,
        default:function(){
          return new Object();
        }
      },
    },
    data () {
      return {
        //value:'',
        options:[]
      };
    },
    // mounted(){
    //   let val=this.selvalue;
    //   this.value = val;
    // },
    created(){
      //获取字典数据
      this.initDictData();
    },
    methods: {
      handleValueShow (arr, showKeys) {
        let selectItems = []
        let arr_keys = showKeys.split(',')
        for (let i = 0; i < arr_keys.length; i++) {
          let key = arr_keys[i]
          for (let j = 0; j < arr.length; j++) {
            let item = arr[j]
            if (item.value == key) {
              selectItems.push(item)
            }
          }
        }
        return selectItems
      },
      handleValueHide (arr, hideKeys) {
        if (hideKeys != null && hideKeys != '') {
          let arr_keys = hideKeys.split(',')
          for (let j = 0; j < arr.length; j++) {
            let item = arr[j]
            for (let i = 0; i < arr_keys.length; i++) {
              let key = arr_keys[i]
              if (item.value == key) {
                arr.splice(j--, 1)
              }
            }
          }
        }
        return arr
      },
      changeFun(data){//下拉框值发生改变时调用
        if(typeof(data)!= 'undefined'){
          this.$emit('update:bindData',data.value);
          this.$emit('changeState',data);//data有value和label
        }
      },
      changeSearch(query){//搜索词改变时触发,***注意这个事件想触发，不要传sel_val，我们搜索的同时，他会给赋值，造成冲突报错
        let str = {
          'text':query
        }
        this.$emit('changeSearch',str);
      },
      clearFun(){//点击清空按钮时触发
        this.$emit('update:bindData','');
      },
      openChangeFun(data){//true / false
        this.$emit('openChangeFun',data);
      },
      //获取字典信息
      getDictList() {
        var that = this;
        if (sessionStorage.getItem("sys_dict_list")) {
          this.dictList = JSON.parse(sessionStorage.getItem("sys_dict_list"));
          that.getDictListByCode();
        } else {
          postAction('/api/ac/subsistence/extSysDictService/getDictList', {}).then((res) => {
            if (res.data.errcode == 0) {
              that.dictList = res.data.data;
              sessionStorage.setItem("sys_dict_list", JSON.stringify(that.dictList));
              that.getDictListByCode();
            }
          })
        }
      },
      //根据字典code获取字典列表
      getDictListByCode() {
        let that=this;
        let showKeys=that.showKeys;
        let hideKeys=that.hideKeys;
        if (that.dictCode) {
          var dictList = this.dictList;
          var optionList = [];
          for (var i in dictList) {
            if (dictList[i].type == this.dictCode) {
              optionList.push(dictList[i]);
            }
          }
          that.options = optionList;

          if(showKeys!=null&&showKeys!=''){
            that.options = that.handleValueShow(that.options,showKeys);
          }
          if(hideKeys!=null&&hideKeys!=''){
            that.options = that.handleValueHide(that.options,hideKeys);
          }
        }
      },
      initDictData(){
        let that=this;
        let param={};
        let showKeys=that.showKeys;
        let hideKeys=that.hideKeys;
        if(that.dicType =='code'){
          /*
          param.pageNo=1;// 当前页数
          param.pageSize=999;//每页显示条数
          param.type=that.dictCode; //字典type值（例如：assp0004）
          postAction('/api/as/sc/dict/getDictList', param).then((res) => {
            if (res.data.errcode === 0) {
              that.options=res.data.data.results;
              if(showKeys!=null&&showKeys!=''){
                that.options = that.handleValueShow(res.data.data.results,showKeys);
              }
              if(hideKeys!=null&&hideKeys!=''){
                that.options = that.handleValueHide(res.data.data.results,hideKeys);
              }
            }
          })*/
          that.getDictList();
        }else if(that.dicType =='table'){
          let param={};
          param.keywords=that.dictTable;
          postAction('/api/ac/subsistence/extSysDictService/getTableDictList', param).then((res) => {
            if (res.data.errcode === 0) {
              if(res.data.data.code===1){
                if(showKeys!=null&&showKeys!=''){
                  that.options = that.handleValueShow(res.data.data.results,showKeys);
                }else
                if(hideKeys!=null&&hideKeys!=''){
                  that.options = that.handleValueHide(res.data.data.results,hideKeys);
                }else{
                  that.options=res.data.data.results;
                }
              }
            }
          })
        }else if(that.dicType =='service'){
          let param=that.serviceParam;
          let url=that.dictService;
          postAction(url, param).then((res) => {
            if (res.data.errcode === 0) {
              if(showKeys!=null&&showKeys!=''){
                that.options = that.handleValueShow(res.data.data.results,showKeys);
              }else
              if(hideKeys!=null&&hideKeys!=''){
                that.options = that.handleValueHide(res.data.data.results,hideKeys);
              }else{
                that.options=res.data.data.results;
              }
            }
          })
        }
      },
    },
    watch: {}
  }
</script>
<style lang='less' scoped>
</style>
